package com.block.source.service.receive;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.block.common.enums.BaseTypeInfoEnum;
import com.block.common.model.vo.ResultInfoVO;
import com.block.common.service.IAddressInfoService;
import com.block.common.service.IApplicationInfoService;
import com.block.common.service.IChannelCommonService;
import com.block.common.util.AESUtil;
import com.block.db.entity.*;
import com.block.db.mapper.SourcePushResultInfoMapper;
import com.block.source.model.api.JiQiongBaoParam;
import com.block.source.model.dto.SourceApiParam;
import com.block.source.model.dto.SourceApiResult;
import com.block.source.model.param.UserDataParam;
import com.block.source.service.ISourceReceiveService;
import com.block.source.utils.JyhDsAESUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Map;
import java.util.UUID;

@Service
public class CaiMiYouJinReceiveService extends ISourceReceiveService {

    @Autowired
    IAddressInfoService addressInfoService;
    @Resource
    SourcePushResultInfoMapper sourcePushResultInfoMapper;
    @Autowired
    IChannelCommonService channelCommonService;
    @Autowired
    IApplicationInfoService applicationInfoService;


    @Override
    public SourceApiResult handleCheckUserData(SourceBaseInfo sourceBaseInfo, Map<String, String[]> parameterMap, String paramContent) {
        SourceApiResult sourceApiResult = new SourceApiResult();
        sourceApiResult.setSuccess(false);

        String apiSecretSubstring = sourceBaseInfo.getApiSecret();
        String iv = sourceBaseInfo.getApiKey();

        JSONObject jsonObjectParamContent = JSONObject.parseObject(paramContent);
        if (ObjectUtil.isEmpty(jsonObjectParamContent)){
            sourceApiResult.setReturnObject(this.getCheckAndRegister(402,"撞库传入的信息为空",null,null));
            return sourceApiResult;
        }

        String channel = jsonObjectParamContent.getString("channel");
        String encryptData = jsonObjectParamContent.getString("encrypt_data");
        Integer timestamp = jsonObjectParamContent.getInteger("timestamp");
        String sign = jsonObjectParamContent.getString("sign");
        String traceId = jsonObjectParamContent.getString("trace_id");
        boolean isSign = verify(sign, jsonObjectParamContent);

        if (!isSign) {
            sourceApiResult.setReturnObject(this.getCheckAndRegister(401,"撞库签名错误",null,null));
            return sourceApiResult;
        }

        String paramContentData = null;
        try {
            paramContentData = AESUtil.decryptBase64(encryptData, apiSecretSubstring, iv);
        } catch (Exception e) {
            e.printStackTrace();
        }


        JSONObject jsonObject = JSONObject.parseObject(paramContentData);
        //过滤
        if (StrUtil.isEmpty(jsonObject.getString("mobileMd5")) || StrUtil.isEmpty(jsonObject.getString("cityCode"))){
            sourceApiResult.setReturnObject(this.getCheckAndRegister(402,"撞库传入的信息有空值",null,null));
            return sourceApiResult;
        }

        JSONObject jsonObject1 = JSONObject.parseObject(paramContentData);
        jsonObject1.put("reqNo",jsonObjectParamContent.getString("reqNo"));
        String paramContentData1 = JSON.toJSONString(jsonObject1);
        UserDataParam userDataParam = this.getUserDataParam(paramContentData1);


        // 通过城市编码,获取城市信息
        AddressInfo addressInfo = addressInfoService.getAddressInfoByCityCode(userDataParam.getCityCode());
        if (ObjectUtil.isEmpty(addressInfo)) {
            sourceApiResult.setReturnObject(this.getCheckAndRegister(402,"城市信息为空",null,null));
            return sourceApiResult;
        }

        // 设置省市信息
        userDataParam.setCityCode(addressInfo.getCityCode());
        userDataParam.setCity(addressInfo.getCity());
        userDataParam.setProvinceCode(addressInfo.getProvinceCode());
        userDataParam.setProvince(addressInfo.getProvince());
        sourceApiResult.setUserDataParam(userDataParam);
        sourceApiResult.setSuccess(true);

        return sourceApiResult;
    }

    @Override
    public SourceApiResult handleRegisterUserData(SourceBaseInfo sourceBaseInfo, Map<String, String[]> parameterMap, String paramContent) {

        SourceApiResult sourceApiResult = new SourceApiResult();
        sourceApiResult.setSuccess(false);

        String apiSecretSubstring = sourceBaseInfo.getApiSecret();
        String iv = sourceBaseInfo.getApiKey();

        JSONObject jsonObjectParamContent = JSONObject.parseObject(paramContent);
        if (ObjectUtil.isEmpty(jsonObjectParamContent)){
            sourceApiResult.setReturnObject(this.getCheckAndRegister(402,"进件传入的信息为空",null,null));
            return sourceApiResult;
        }

        String data = jsonObjectParamContent.getString("data");
        String sign = jsonObjectParamContent.getString("sign");
        boolean isSign = verify(sign, jsonObjectParamContent);

        if (!isSign) {
            sourceApiResult.setReturnObject(this.getCheckAndRegister(401,"进件签名错误",null,null));
            return sourceApiResult;
        }

        String paramContentData = null;
        try {
            paramContentData = AESUtil.decryptBase64(data, apiSecretSubstring, iv);
        } catch (Exception e) {
            e.printStackTrace();
        }


        JSONObject jsonObject1 = JSONObject.parseObject(paramContentData);
        jsonObject1.put("reqNo",jsonObjectParamContent.getString("reqNo"));
        String paramContentData1 = JSON.toJSONString(jsonObject1);

        JiQiongBaoParam jiQiongBaoParam = JSON.parseObject(paramContentData1, JiQiongBaoParam.class);

        UserDataParam userDataParam = this.getUserDataParam(paramContentData1);

        userDataParam.setMobile(jiQiongBaoParam.getMobile());
        userDataParam.setRealName(jiQiongBaoParam.getRealName());

        String reqNo = jiQiongBaoParam.getReqNo();
        SourcePushResultInfo pushResultInfo = sourcePushResultInfoMapper.selectByChannelCodeAndOutOrderNo(sourceBaseInfo.getChannelCode(), reqNo);
        userDataParam.setOrderNo(String.valueOf(pushResultInfo.getId()));

        sourceApiResult.setUserDataParam(userDataParam);
        sourceApiResult.setSuccess(true);

        return sourceApiResult;
    }

    @Override
    public SourceApiResult getCheckUserReturnData(SourceBaseInfo sourceBaseInfo, ResultInfoVO resultInfoVO, SourceApiParam sourceApiParam) {


        SourceApiResult sourceApiResult = new SourceApiResult();



        JSONObject success = this.getCheckSuccess(200, "success", 1, UUID.randomUUID().toString(),sourceApiParam,sourceBaseInfo);

        sourceApiResult.setReturnObject(success);


        return sourceApiResult;
    }

    @Override
    public SourceApiResult getRegisterUserReturnData(SourceBaseInfo sourceBaseInfo, ResultInfoVO resultInfoVO,SourceApiParam sourceApiParam) {
        SourceApiResult sourceApiResult = new SourceApiResult();

        JSONObject data = resultInfoVO.getData();
        String respCode = resultInfoVO.getRespCode();

        if (StrUtil.equals(respCode, "200") && resultInfoVO.isSuccess()){
            String status = data.getString("status");
            if (StrUtil.equals(status, "000")){
                JSONObject success = this.getCheckAndRegister(200, "success", 1, UUID.randomUUID().toString());
                sourceApiResult.setReturnObject(success);
                return sourceApiResult;
            }
        }
        JSONObject error = this.getCheckAndRegister(200, "success", 99, UUID.randomUUID().toString());
        sourceApiResult.setReturnObject(error);

        return sourceApiResult;
    }

    @Override
    public JSONObject getError(String message) {
        JSONObject returnObject = new JSONObject();
        return returnObject;
    }

    @Override
    public JSONObject getSuccess() {
        JSONObject returnObject = new JSONObject();
        return returnObject;
    }

    @Override
    public UserDataParam getUserDataParam(String paramContent) {

        JiQiongBaoParam jiQiongBaoParam = JSON.parseObject(paramContent, JiQiongBaoParam.class);

        UserDataParam userDataParam = new UserDataParam();

        userDataParam.setOutOrderNo(jiQiongBaoParam.getReqNo());

        userDataParam.setMobileMd5(jiQiongBaoParam.getMobileMd5());
        userDataParam.setMobile(jiQiongBaoParam.getMobile());
        userDataParam.setRealName(jiQiongBaoParam.getRealName());

        userDataParam.setSex(String.valueOf(jiQiongBaoParam.getSex()));


        userDataParam.setAge(jiQiongBaoParam.getAge());
        userDataParam.setCityCode(jiQiongBaoParam.getCityCode());


        userDataParam.setXinyongka(BaseTypeInfoEnum.XinYongKa.xyk001.getValue());


        userDataParam.setYongtu(BaseTypeInfoEnum.Yongtu.yt007.getValue());
        userDataParam.setXueli(BaseTypeInfoEnum.XueLi.xl001.getValue());
        userDataParam.setShouru(BaseTypeInfoEnum.Shouru.sr001.getValue());
        userDataParam.setWeili(BaseTypeInfoEnum.WeiLi.wl001.getValue());
        userDataParam.setBaitiao(BaseTypeInfoEnum.Baitiao.bt001.getValue());
        userDataParam.setHuabei(BaseTypeInfoEnum.Huabei.hb001.getValue());

        String clientIp = jiQiongBaoParam.getClientIp();
        if (StringUtils.isEmpty(clientIp)){
            userDataParam.setUserIp("127.0.0.1");
        }else{
            userDataParam.setUserIp(jiQiongBaoParam.getClientIp());
        }

//        String loanAmount = jiQiongBaoParam.getLoanAmount();
//        if (StringUtils.isEmpty(loanAmount)){
//            userDataParam.setLoanAmount(BaseTypeInfoEnum.LoanAmount.la001.getValue());
//        }else {
//            String intNumber = loanAmount.substring(0,loanAmount.indexOf("."));
//            if (Integer.valueOf(intNumber) <= 3) {
//                userDataParam.setLoanAmount(BaseTypeInfoEnum.LoanAmount.la001.getValue());
//            } else if (Integer.valueOf(intNumber) > 3 && Integer.valueOf(intNumber) <= 5) {
//                userDataParam.setLoanAmount(BaseTypeInfoEnum.LoanAmount.la002.getValue());
//            } else if (Integer.valueOf(intNumber) > 5 && Integer.valueOf(intNumber) <= 10) {
//                userDataParam.setLoanAmount(BaseTypeInfoEnum.LoanAmount.la003.getValue());
//            } else if (Integer.valueOf(intNumber) >10 && Integer.valueOf(intNumber) <= 20) {
//                userDataParam.setLoanAmount(BaseTypeInfoEnum.LoanAmount.la004.getValue());
//            } else {
//                userDataParam.setLoanAmount(BaseTypeInfoEnum.LoanAmount.la005.getValue());
//            }
//
//        }

        String loanAmount = jiQiongBaoParam.getLoanAmount();
        if (StringUtils.isEmpty(loanAmount)){
            userDataParam.setLoanAmount(BaseTypeInfoEnum.LoanAmount.la001.getValue());
        }else {
            if (Integer.valueOf(loanAmount) <= 30000) {
                userDataParam.setLoanAmount(BaseTypeInfoEnum.LoanAmount.la001.getValue());
            } else if (Integer.valueOf(loanAmount) > 30000 && Integer.valueOf(loanAmount) <= 50000) {
                userDataParam.setLoanAmount(BaseTypeInfoEnum.LoanAmount.la002.getValue());
            } else if (Integer.valueOf(loanAmount) > 50000 && Integer.valueOf(loanAmount) <= 100000) {
                userDataParam.setLoanAmount(BaseTypeInfoEnum.LoanAmount.la003.getValue());
            } else if (Integer.valueOf(loanAmount) >100000 && Integer.valueOf(loanAmount) <= 200000) {
                userDataParam.setLoanAmount(BaseTypeInfoEnum.LoanAmount.la004.getValue());
            } else {
                userDataParam.setLoanAmount(BaseTypeInfoEnum.LoanAmount.la005.getValue());
            }

        }

        Integer houseProperty = jiQiongBaoParam.getHasHouse();
        if (houseProperty == null){
            userDataParam.setHouse(BaseTypeInfoEnum.House.hu001.getValue());
        }else {
            if ("0".equals(String.valueOf(houseProperty))){
                userDataParam.setHouse(BaseTypeInfoEnum.House.hu001.getValue());
            }else{
                userDataParam.setHouse(BaseTypeInfoEnum.House.hu003.getValue());
            }
        }


        Integer hasInsurance = jiQiongBaoParam.getHasInsurance();
        if (hasInsurance == null){
            userDataParam.setBaoxian(BaseTypeInfoEnum.Baoxian.bx001.getValue());
        }else {
            if ("0".equals(String.valueOf(hasInsurance))){
                userDataParam.setBaoxian(BaseTypeInfoEnum.Baoxian.bx001.getValue());
            }else {
                userDataParam.setBaoxian(BaseTypeInfoEnum.Baoxian.bx002.getValue());
            }
        }


        userDataParam.setYuqi(BaseTypeInfoEnum.Yuqi.yq001.getValue());

        Integer hasFund = jiQiongBaoParam.getHasFund();
        if (hasFund == null){
            userDataParam.setGjj(BaseTypeInfoEnum.Gjj.gjj001.getValue());
        }else {
            if ("0".equals(String.valueOf(hasFund))){
                userDataParam.setGjj(BaseTypeInfoEnum.Gjj.gjj001.getValue());
            }else{
                userDataParam.setGjj(BaseTypeInfoEnum.Gjj.gjj002.getValue());
            }
        }

        String zhimaCredit = jiQiongBaoParam.getZmfScore();
        if (StringUtils.isEmpty(zhimaCredit)){
            userDataParam.setZhima(BaseTypeInfoEnum.Zhima.zm001.getValue());
        }else {
            if ("700".equals(zhimaCredit)){
                userDataParam.setZhima(BaseTypeInfoEnum.Zhima.zm005.getValue());
            }else if ("699".equals(zhimaCredit)){
                userDataParam.setZhima(BaseTypeInfoEnum.Zhima.zm004.getValue());
            }else if ("650".equals(zhimaCredit)){
                userDataParam.setZhima(BaseTypeInfoEnum.Zhima.zm003.getValue());
            }else if ("600".equals(zhimaCredit)){
                userDataParam.setZhima(BaseTypeInfoEnum.Zhima.zm002.getValue());
            }else{
                userDataParam.setZhima(BaseTypeInfoEnum.Zhima.zm001.getValue());
            }
        }

        Integer hasSocial = jiQiongBaoParam.getHasSocial();
        if (hasSocial == null){
            userDataParam.setShebao(BaseTypeInfoEnum.Shebao.sb001.getValue());
        }else {
            if ("0".equals(String.valueOf(hasSocial))){
                userDataParam.setShebao(BaseTypeInfoEnum.Shebao.sb001.getValue());
            }else{
                userDataParam.setShebao(BaseTypeInfoEnum.Shebao.sb002.getValue());
            }
        }

        Integer hasCar = jiQiongBaoParam.getHasCar();
        if (hasCar == null){
            userDataParam.setCar(BaseTypeInfoEnum.Car.car001.getValue());
        }else {
            if ("0".equals(String.valueOf(hasCar))){
                userDataParam.setCar(BaseTypeInfoEnum.Car.car001.getValue());
            }else{
                userDataParam.setCar(BaseTypeInfoEnum.Car.car002.getValue());
            }
        }

        Integer hasCompany = jiQiongBaoParam.getHasCompany();
        if (hasCompany == null){
            userDataParam.setGongzuo(BaseTypeInfoEnum.Gongzuo.gz001.getValue());
        }else {
            if ("1".equals(String.valueOf(hasCompany))){
                userDataParam.setGongzuo(BaseTypeInfoEnum.Gongzuo.gz002.getValue());
            }else {
                userDataParam.setGongzuo(BaseTypeInfoEnum.Gongzuo.gz001.getValue());
            }
        }

        userDataParam.setLoanTime(BaseTypeInfoEnum.LoanTime.lt001.getValue());


        return userDataParam;
    }

    /**
     * 验证签名
     *
     * @param sign 签名
     * @param objJson 请求参数
//     * @param secretKey 密钥
     * @return true/false
     * @date 2024/3/28
     */
    public static boolean verify(String sign, JSONObject objJson) {
        String channel = objJson.getString("channel");
        String encryptData = objJson.getString("encrypt_data");
        Integer timestamp = objJson.getInteger("timestamp");
        String traceId = objJson.getString("trace_id");

        return sign.equals(null);
    }

    public JSONObject getCheckAndRegister(Integer code,String message,Integer status,String orderNo) {
        JSONObject returnObject = new JSONObject();
        returnObject.put("code",code);
        returnObject.put("msg", message);
        JSONObject dataJson = new JSONObject();
        if (code == 200){
            dataJson.put("status",status);
            dataJson.put("orderNo",orderNo);
        }
        returnObject.put("data",dataJson);
        return returnObject;
    }

    public JSONObject getCheckSuccess(Integer code,String message,Integer status,String orderNo,SourceApiParam sourceApiParam,SourceBaseInfo sourceBaseInfo) {
        JSONObject returnObject = new JSONObject();
        returnObject.put("code",code);
        returnObject.put("msg", message);
        JSONObject dataJson = new JSONObject();
        if (code == 200){
            dataJson.put("status",status);
            dataJson.put("orderNo",orderNo);
            MerchantBaseInfo merchantBaseInfo = sourceApiParam.getMerchantBaseInfo();
            SourcePushResultInfo pushResultInfo = sourceApiParam.getSourcePushResultInfo();
            dataJson.put("productName", merchantBaseInfo.getInfoName());
            dataJson.put("companyName", merchantBaseInfo.getCompanyName());
            //协议地址
            JSONArray jsonArray = new JSONArray();
            JSONObject jsonObject = new JSONObject();
            ChannelBaseInfo baseInfoByCode = channelCommonService.getBaseInfoByCode(sourceBaseInfo.getChannelCode());
            ApplicationInfo appInfoByAppCode = applicationInfoService.getAppInfoByAppCode(baseInfoByCode.getAppCode());
            String protocolUrl = StrUtil.format("{}/page/newprotocol/{}/{}.html", appInfoByAppCode.getApiUrl(), pushResultInfo.getOrderNo(), pushResultInfo.getOrderItemNo());
            jsonObject.put("contractName","授权协议");
            jsonObject.put("contractUrl", protocolUrl);
            jsonArray.add(jsonObject);
            dataJson.put("contractList", jsonArray);
        }
        returnObject.put("data",dataJson);
        return returnObject;
    }






}
